<?php
namespace Admin\Controller;

use Think\Controller;

class UserController extends Controller
{
    private $user;

    public function __construct()
    {
        parent::__construct();
        $this->user = M("user");
    }


    public function register()
    {
        $this->display();
    }


    public function do_register()
    {
        $User = D('User');

        if (!$User->create()) {
            $this->error($User->getError());
        } else {
            $User->add();
            $this->success("注册成功", U('login'));
        }
    }

    public function login()
    {
        $this->display();
    }

    public function do_login()
    {
        $code = I("post.code");
        if (!$this->check_verify($code)) {
            $this->error('验证码错误');
        }

        $data['email'] = I("post.email");
        $data['password'] = substr(md5(I("post.password")), 6, -6);
        $user = $this->user->where($data)->find();
        if (!$user) {
            $this->error("账号或密码错误");
        }

        cookie('token', $user['token'], 60 * 60 * 24 * 7);
        $this->success('登录成功', U("Admin/Index/index"));
    }

    //生成验证码
    public function verify()
    {
        $Verify = new \Think\Verify(C('verify'));
        $Verify->entry();
    }


    //检测验证码是否正确
    function check_verify($code, $id = '')
    {
        $verify = new \Think\Verify();
        return $verify->check($code, $id);
    }

    function logout()
    {
        $_SESSION = array();
        cookie(session_name(), null);
        cookie('token', null);
        $this->success('您已经安全退出', U('login'));
    }

}
